//
//  FindingViewController.m
//  DianNaoWang
//
//  Created by dllo on 15/11/2.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "FindingViewController.h"
#import "Header.h"
#import "CFNetworkFromAFNetworking.h"
#import "ProductClassModel.h"
#import "ProductListModel.h"
#import "SectionTitleModel.h"
#import "SearchViewController.h"
#import "UIImageView+WebCache.h"
#import "SearchBarViewController.h"
#import "ReplaceSearchBarView.h"
#import "DataBaseManager.h"
#import "MBProgressHUD.h"
#import "WebViewController.h"
@interface FindingViewController ()<UITableViewDataSource,UITableViewDelegate>
@property(nonatomic, retain)UITableView *productClassTableView;
@property(nonatomic, retain)UITableView *detailedProductListTableView;
@property(nonatomic, retain)NSMutableArray *classDataSourceArray;
@property(nonatomic, retain)NSMutableArray *detailedDataSourceArray;
@property(nonatomic, retain)NSArray *productListArray;
@property(nonatomic, retain)NSMutableArray *productSectionArray;
@property(nonatomic, retain)NSString *page;
@property(nonatomic, retain)ReplaceSearchBarView *replaceSBView;
@property(nonatomic, retain)UITableView *favoritTableView;
@property(nonatomic, retain)NSMutableArray *favArray;
@property(nonatomic, retain)UILabel *footlabel;
@property(nonatomic, retain)UIView *backView;
@property(nonatomic, retain)MBProgressHUD *HUD;
@end

@implementation FindingViewController

-(void)loadView
{
    [super loadView];
    self.view.backgroundColor = BackgroundColor;
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController.navigationBar setTintColor:[UIColor whiteColor]];
    self.automaticallyAdjustsScrollViewInsets = NO;//创建时布局{如果不加这个,productClassTableview的高度就不能减49,detailedProductListTableView却要减  为什么????}
    self.classDataSourceArray = [NSMutableArray array];
    self.detailedDataSourceArray = [NSMutableArray array];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
#pragma mark 共有两个tableView 一个是产品类别表,另一个是产品列表或者产品的详细类表(如:*手机--{苹果 三星} *大家电{空调 平板电视})
    self.detailedProductListTableView = [[UITableView alloc]initWithFrame:CGRectMake(ScreenWidth / 3 + 10 * FitWidth, 10 * FitHeight, ScreenWidth * 2 / 3 - 10 * FitWidth, ScreenHeight - (49 + 64) - 10 * FitHeight)];
    _detailedProductListTableView.delegate = self;
    _detailedProductListTableView.dataSource = self;
    _detailedProductListTableView.showsHorizontalScrollIndicator = NO;
    _detailedProductListTableView.showsVerticalScrollIndicator = NO;
    _detailedProductListTableView.tableFooterView = [[UIView alloc]init];
    _detailedProductListTableView.backgroundColor = BackgroundColor;
    [self.view addSubview:_detailedProductListTableView];

    
    self.productClassTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - (49 + 64))];
    _productClassTableView.backgroundColor = BackgroundColor;
    _productClassTableView.delegate = self;
    _productClassTableView.dataSource = self;
    _productClassTableView.showsVerticalScrollIndicator = NO;
    _productClassTableView.showsHorizontalScrollIndicator = NO;
    _productClassTableView.tableFooterView = [[UIView alloc]init];
    [self.view addSubview:_productClassTableView];

    
    
    [self getClassDataArray];
    
    //制作最近浏览的tableView
    self.favoritTableView = [[UITableView alloc]initWithFrame:CGRectMake(ScreenWidth / 3 + 10 * FitWidth, 10 * FitHeight, 0, ScreenHeight - (49 + 64) - 10 * FitHeight)];
    _favoritTableView.delegate = self;
    _favoritTableView.dataSource = self;
    _favoritTableView.showsHorizontalScrollIndicator = NO;
    _favoritTableView.showsVerticalScrollIndicator = NO;
    _favoritTableView.tableFooterView = [[UIView alloc]init];
    _favoritTableView.backgroundColor = BackgroundColor;
    [self.view addSubview:_favoritTableView];

    
    self.footlabel = [[UILabel alloc]initWithFrame:CGRectMake(80, 10, 175, 20)];
    if ([DataBaseManager selectPrice].count > 0) {
        _footlabel.text = @"清除记录";
    }else{
        _footlabel.text = @"没有浏览记录";
    }
    
    _footlabel.font = [UIFont systemFontOfSize:12];
    _footlabel.userInteractionEnabled = YES;
    UITapGestureRecognizer *tapToClearn = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapToclearnAction)];
    [_footlabel addGestureRecognizer:tapToClearn];
    _favoritTableView.tableFooterView = _footlabel ;
    
#pragma mark 设置一个假的 searchbar
    _replaceSBView = [[ReplaceSearchBarView alloc]initWithFrame:CGRectMake(0, 0, 265, 25)];
    _replaceSBView.layer.cornerRadius = 5;
    self.navigationItem.titleView = _replaceSBView;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tapAction)];
    [_replaceSBView addGestureRecognizer:tap];

    
#pragma mark 菊花
    //UIActivityIndicatorViewStyleWhiteLarge,
    //UIActivityIndicatorViewStyleWhite,
    //UIActivityIndicatorViewStyleGray,
    _activityView = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    _activityView.center = CGPointMake(ScreenWidth / 2, ScreenHeight / 2 - 64 * FitHeight);
    [self.view addSubview:_activityView];
    
    _HUD = [MBProgressHUD showHUDAddedTo:self.view  animated:YES];
    _HUD.labelText = @"正在加载";
    _HUD.detailsLabelText = @"请耐心等待";
    _HUD.backgroundColor = [UIColor clearColor];
    
    //夜间模式的监听者
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(colorChange) name:@"colorChange" object:nil];
}
#pragma mark - 夜间模式 监听到变化后采取的措施
- (void )colorChange
{
    self.view.backgroundColor = BackgroundColor;
    _productClassTableView.backgroundColor = BackgroundColor;
    [_productClassTableView reloadData];
    _detailedProductListTableView.backgroundColor = BackgroundColor;
    [_detailedProductListTableView reloadData];
    _favoritTableView.backgroundColor = BackgroundColor;
    [_favoritTableView reloadData];
    
}


#pragma mark 点击清除记录 清除数据库
-(void)tapToclearnAction
{
    _favArray = nil;
    [_favoritTableView reloadData];
    _footlabel.text = @"没有浏览记录";
    NSArray *Array = [DataBaseManager selectPrice];
    for (FavoriteWapPage *fwp in Array) {
        [DataBaseManager deleteFavoritePricePage:fwp];
    }
    
}

//搜索框的tap事件
-(void)tapAction
{
    SearchBarViewController *sbVC = [[SearchBarViewController alloc]init];
    sbVC.keyID = 2;
    sbVC.modalTransitionStyle = 2;
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:sbVC];
    [self presentViewController:nav animated:YES completion:NULL];
    //[self presentViewController:sbVC animated:YES completion:nil];
}

#pragma mark 关于tableView
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == _favoritTableView) {
        return _favArray.count;
    }
    if (tableView == _productClassTableView) {
        return _classDataSourceArray.count;
    }else{
        if (_productSectionArray != nil) {
            return [[_productSectionArray[section] detaileArray] count];
        }else return _productListArray.count;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _productClassTableView) {
        return 50 * FitHeight;
    }else return 60 * FitHeight;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == _favoritTableView) {
        static NSString *identifier0 = @"cell0";
        UITableViewCell *cell0 = [tableView dequeueReusableCellWithIdentifier:identifier0];
        if (!cell0) {
            cell0 = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier0];
        }
        cell0.backgroundColor = BackgroundColor;
        cell0.textLabel.textColor = contenttextColor;
        cell0.textLabel.text = [_favArray[indexPath.row] title];
        return cell0;
    }
    if (tableView == _productClassTableView) {
        static NSString *identifier1 = @"cell1";
        UITableViewCell *cell1 = [tableView dequeueReusableCellWithIdentifier:identifier1];
        if (!cell1) {
            cell1 = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier1];
            
            cell1.textLabel.font = contentTextSize;
        }
        
        if ([[NSUserDefaults standardUserDefaults]boolForKey:@"nightIsOn"]) {
            cell1.backgroundColor = BackgroundColor;
            _backView = [[UIView alloc]initWithFrame:cell1.frame];
            _backView.backgroundColor = GrayerColor;
            cell1.selectedBackgroundView = _backView;
        }else{
            _backView = [[UIView alloc]initWithFrame:cell1.frame];
            _backView.backgroundColor = BackgroundColor;
            cell1.selectedBackgroundView = _backView;
            cell1.backgroundColor = [UIColor colorWithRed:0.97 green:0.97 blue:0.97 alpha:1];
        }
        
        cell1.textLabel.textColor = contenttextColor;
        cell1.textLabel.text = [_classDataSourceArray[indexPath.row] name];
        return cell1;
    }else{
        if (_productSectionArray != nil) {
            if (indexPath.section <= 1) {
                static NSString *identifier2 = @"cell2";
                UITableViewCell *cell2 = [tableView dequeueReusableCellWithIdentifier:identifier2];
                if (!cell2) {
                    cell2 = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier2];
                }
                cell2.textLabel.text = [[[_productSectionArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row] name];
                cell2.backgroundColor = GrayerColor;
                cell2.textLabel.textColor = contenttextColor;
                cell2.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
                return cell2;
            }else{
                static NSString *identifier3 = @"cell3";
                UITableViewCell *cell3 = [tableView dequeueReusableCellWithIdentifier:identifier3];
                if (!cell3) {
                    cell3 = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier3];
                }
                cell3.backgroundColor = GrayerColor;
                cell3.textLabel.textColor = contenttextColor;
                cell3.textLabel.text = [[[_productSectionArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row] name];
                return cell3;
            }
        }else {
            static NSString *identifier4 = @"cell4";
            UITableViewCell *cell4 = [tableView dequeueReusableCellWithIdentifier:identifier4];
            if (!cell4) {
                cell4 = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier4];
            }
            cell4.backgroundColor = GrayerColor;
            cell4.textLabel.textColor = contenttextColor;
            cell4.textLabel.text = [_productListArray[indexPath.row] name];
            return cell4;
        }
    }
}

#pragma mark 点击第一排给第二排赋值,点第二排去下一页 并传值
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [_detailedProductListTableView deselectRowAtIndexPath:indexPath animated:NO];
    [_favoritTableView deselectRowAtIndexPath:indexPath animated:NO];
    if (tableView == _favoritTableView) {
        WebViewController *webView = [[WebViewController alloc]init];
        //存时将id存为wapurlstring了
        if (_favArray.count > 0) {
            webView.Id = [_favArray[indexPath.row] wapUrlString];
            [self.navigationController pushViewController:webView animated:YES];
        }
        return;
    }
    _favoritTableView.frame = CGRectZero;
    if (tableView == _productClassTableView) {
        [UIView animateWithDuration:.3 animations:^{
            _productClassTableView.frame = CGRectMake(0, 0, ScreenWidth / 3, ScreenHeight - (49 + 64));
        }];
        
        if (indexPath.row == 0) {
            [DataBaseManager creatPriceTable];
            self.favArray = [DataBaseManager selectPrice];
            if (_favArray.count > 0) {
                _footlabel.text = @"清除记录";
            }else{
                _footlabel.text = @"没有浏览记录";
            }
            _favoritTableView.frame = CGRectMake(ScreenWidth / 3 + 10 * FitWidth, 10 * FitHeight,  ScreenWidth * 2 / 3 - 10 * FitWidth, ScreenHeight - (49 + 64) - 10 * FitHeight);
            [_favoritTableView reloadData];
            return;
        }
        //点击第一排给第二排赋值
        if ([_classDataSourceArray[indexPath.row] subArr] == nil) {
            //如果subArray为空,是排序列表
            [self getDetailedDataArrayAfterClickTypNoArr:_classDataSourceArray[indexPath.row]];
            _activityView.center = CGPointMake(ScreenWidth * 2 / 3, _detailedProductListTableView.frame.size.height / 2);
            [_activityView startAnimating];
        }else{
            //如果不为空,是分类列表(subArray里存的ProductDetaileClassdModel)
            [_activityView stopAnimating];
            [self getDetailedDataArrayAfterClickTypeSubArr:_classDataSourceArray[indexPath.row]];
        }
    }else{
        //点击第二排,推出Viewcontroller,传过去list类
        if (_productListArray == nil && _productSectionArray != nil && indexPath) {
            //传的是ProductListModel类 有两个id
            if (indexPath.section < 2) {
                SearchViewController *svc = [[SearchViewController alloc]init];
                svc.PLM = [[_productSectionArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row];
                svc.allProductArray = _productSectionArray;
                [self.navigationController pushViewController:svc animated:YES];
            }else{
                ////NSLog(@"%@", [[[_productSectionArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row] name]);
                SearchViewController *svc = [[SearchViewController alloc]init];
                svc.PLM = [[_productSectionArray[indexPath.section] detaileArray] objectAtIndex:indexPath.row];
                svc.allProductArray = _productSectionArray;
                [self.navigationController pushViewController:svc animated:YES];
            }
            
        }
        
        if (_productSectionArray == nil && _productListArray != nil && indexPath) {
            ////NSLog(@"大家电%@", [_productListArray[indexPath.row] name]);
            SearchViewController *Svc = [[SearchViewController alloc]init];
            Svc.PLM = _productListArray[indexPath.row];//ProductListModel类 有两个Id
            Svc.allProductArray = nil;
            [self.navigationController pushViewController:Svc animated:YES];
        }
        
    }
}

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    if (tableView == _favoritTableView) {
        return 1;
    }
    if (tableView == _detailedProductListTableView) {
        if (_productSectionArray != nil) {
            return _productSectionArray.count;
        }else return 1;
    }else return 1;
    
}

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (tableView == _detailedProductListTableView) {
        if (_productSectionArray.count != 0) {
            return [_productSectionArray[section] sectionTitle];
        }else return NULL;
    }else return nil;
}

-(NSArray<NSString *> *)sectionIndexTitlesForTableView:(UITableView *)tableView
{
    if (tableView == _detailedProductListTableView) {
        if (_productSectionArray.count > 1) {
            NSMutableArray *sectionArray = [NSMutableArray array];
            for (SectionTitleModel *stM in _productSectionArray) {
                if (stM.sectionTitle != nil) {
                    [sectionArray addObject:[stM.sectionTitle substringToIndex:1]];
                }
            }
            return sectionArray;
        }
        
    }
    return nil;
}

#pragma mark 获取第一排数据
- (void)getClassDataArray
{
    NSString *urlString = @"http://lib3.wap.zol.com.cn/index.php?c=Advanced_SubcateList_V1&noParam=1";
    [CFNetworkFromAFNetworking askObjectByURLString:urlString BodyString:nil WithObjectBlock:^(id object) {
        for (NSDictionary *dic in object) {
            ProductClassModel *classM = [[ProductClassModel alloc]init];
            [classM setValuesForKeysWithDictionary:dic];
            classM.subArr = nil;
            if ([dic objectForKey:@"subArr"]) {
                NSArray *array = [dic objectForKey:@"subArr"];
                classM.subArr = [NSMutableArray array];
                //                for (NSDictionary *dict in array) {
                //                    ProductDetaileClassdModel *detaeledM = [[ProductDetaileClassdModel alloc]init];
                //                    [detaeledM setValuesForKeysWithDictionary:dict];
                //                    [classM.subArr addObject:detaeledM];
                //                    [detaeledM release];
                //                }
                for (NSDictionary *dict in array) {
                    //直接将"分类(详细类)"赋值给listModel,方便赋值
                    ProductListModel *detaeledM = [[ProductListModel alloc]init];
                    [detaeledM setValuesForKeysWithDictionary:dict];
                    //标示 为"分类"
                    detaeledM.isPDClassM = YES;
                    
                    [classM.subArr addObject:detaeledM];
                }
                
                
                //                for (ProductDetaileClassdModel *m in classM.subArr) {
                //                    //NSLog(@"%@", m.name);
                //                }
                
            }
            [_classDataSourceArray addObject:classM];
        }
        ProductClassModel *classMHistory = [[ProductClassModel alloc]init];
        classMHistory.name = @"最近浏览";
        [_classDataSourceArray insertObject:classMHistory atIndex:0];
        
        //        for (ProductClassModel *PCm in _classDataSourceArray) {
        //            NSArray *array = PCm.subArr;
        //            for (ProductDetaileClassdModel *pdcM in array) {
        //                //NSLog(@"%@", pdcM.name);
        //            }
        //        }
        
        
        [_productClassTableView reloadData];
        _HUD.hidden = YES;
    }];
}

#pragma mark 获取第二排数据
-(void)getDetailedDataArrayAfterClickTypNoArr:(ProductClassModel *)productClassM;
{
    _productSectionArray = nil;
    self.productListArray = nil;
    [_detailedProductListTableView reloadData];
    //创造排行榜和全部## 的内容和section内容
    //1.排行榜
    //创建详细数组里的对象(只一个)
    ProductListModel *productListM1 = [[ProductListModel alloc]init];
    productListM1.Id = @"paihangbang";
    productListM1.name = @"排行榜";
    productListM1.cateId = productClassM.subId;
    //将创建好的对象装入数组
    NSMutableArray *ArrPaihangbang = [NSMutableArray arrayWithObjects:productListM1, nil];
    //创建排行榜Model并赋值
    SectionTitleModel *stMPaihangbang = [[SectionTitleModel alloc]init];
    stMPaihangbang.sectionTitle = @"排行榜";
    stMPaihangbang.detaileArray = ArrPaihangbang;
    //2.筛选(全部##)
    ProductListModel *productListM2 = [[ProductListModel alloc]init];
    productListM2.Id = @"shaixuan";
    productListM2.cateId = productClassM.subId;
    productListM2.name = [NSString stringWithFormat:@"全部%@", productClassM.name];
    
    NSMutableArray *arrShaixuan = [NSMutableArray arrayWithObjects:productListM2, nil];
    SectionTitleModel *stMShaixuan = [[SectionTitleModel alloc]init];
    stMShaixuan.sectionTitle = @"筛选";
    stMShaixuan.detaileArray = arrShaixuan;
    
    //初始化赋值数组
    self.productSectionArray = [NSMutableArray array];
    //解析数据
    NSString *urlString = [NSString stringWithFormat:@"http://lib3.wap.zol.com.cn/index.php?c=Advanced_Manu_V1&subcateId=%@", productClassM.subId];
    [CFNetworkFromAFNetworking askObjectByURLString:urlString BodyString:nil WithObjectBlock:^(id object) {
        //获取并创建热门列表model
        NSArray *HotArray = [object objectForKey:@"rank"];
        NSMutableArray *hotArrayM = [NSMutableArray array];
        for (NSDictionary *dicti in HotArray) {
            ProductListModel *plM = [[ProductListModel alloc]init];
            [plM setValuesForKeysWithDictionary:dicti];
            plM.cateId = productClassM.subId;
            [hotArrayM addObject:plM];
        }
        SectionTitleModel *hotSTM = [[SectionTitleModel alloc]init];
        hotSTM.sectionTitle = @"热门品牌";
        hotSTM.detaileArray = hotArrayM;
        //创建正常列表Model
        NSDictionary *dic = [object objectForKey:@"abc"];
        //本方法可以变量字典,并获取key和Value
        [dic enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {
            SectionTitleModel *sectionTitleM = [[SectionTitleModel alloc]init];
            sectionTitleM.sectionTitle = key;
            ////NSLog(@"%@", key);
            NSMutableArray *arr = [NSMutableArray array];
            for (NSDictionary *dict in obj) {
                ProductListModel *listM = [[ProductListModel alloc]init];
                [listM setValuesForKeysWithDictionary:dict];
                
                //强行向ProductListModel类里加入cateid和ispdclassM还有方便传入下一页做判断(是点击的分类还是点击的产品)和拼接网址
                listM.cateId = productClassM.subId;
                listM.isPDClassM = NO;
                
                [arr addObject:listM];
            }
            sectionTitleM.detaileArray = arr;
            [self.productSectionArray addObject:sectionTitleM];
        }];
        
        //按分类名排序
        NSComparator sortBlock = ^(id obj1, id obj2){
            SectionTitleModel *sectionTitleM1 = (SectionTitleModel *)obj1;
            SectionTitleModel *sectionTitleM2 = (SectionTitleModel *)obj2;
            if (sectionTitleM1.sectionTitle > sectionTitleM2.sectionTitle) {
                return NSOrderedDescending;
            }else{
                return NSOrderedAscending;
            }
        };
        NSArray *sortdeArr = [_productSectionArray sortedArrayUsingComparator:sortBlock];
        
        //打印验证数组
        /**for (SectionTitleModel *sectionTM in sortdeArr) {
         
         for (ProductListModel *listm in sectionTM.detaileArray) {
         //NSLog(@"%@", listm.name);
         }
         }
         */
        
        //将排行榜 全部## 热门 和排好序的列表数组放进赋值数组中
        self.productSectionArray = [NSMutableArray arrayWithArray:sortdeArr];
        [_productSectionArray insertObject:hotSTM atIndex:0];
        [_productSectionArray insertObject:stMShaixuan atIndex:0];
        [_productSectionArray insertObject:stMPaihangbang atIndex:0];
        
        [_detailedProductListTableView reloadData];
        [_activityView stopAnimating];
    }];
}

-(void)getDetailedDataArrayAfterClickTypeSubArr:(ProductClassModel *)productClassM
{
    _detailedDataSourceArray = nil;
    self.productSectionArray = nil;
    [_detailedProductListTableView reloadData];
    self.productListArray = [NSMutableArray array];
    //    for (ProductListModel *model in productClassM.subArr) {
    //        model.subcateId = productClassM.subId;
    //    }
    
    self.productListArray = productClassM.subArr;
    [_detailedProductListTableView reloadData];
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
